#!/usr/bin/python

import time
import math
import spidev
import RPi.GPIO as GPIO


class PS2(object):

	trans2Read = [0x01, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]

	"""docstring for PS2"""
	def __init__(self, bus, device, cs):
		super(PS2, self).__init__()
		self.bus = bus
		self.device = device
		self.cs = cs

		print("start init", self.cs)

		GPIO.setup(self.cs, GPIO.OUT)
		GPIO.output(self.cs, GPIO.HIGH)



		self.spi = spidev.SpiDev()
		self.spi.open(self.bus, self.device)

		self.spi.max_speed_hz = 50000
		self.spi.mode = 0b10
		self.spi.lsbfirst = True
		self.spi.bits_per_word = 8
		
		print("init done")


	def GetKey(self):
		key = []

		GPIO.output(self.cs, GPIO.LOW)
		key = self.spi.xfer(self.trans2Read)
		GPIO.output(self.cs, GPIO.HIGH)

		print(key)
		return key

	def CleanUp(self):
		spi.close()


if __name__ == '__main__':
	try:
		GPIO.setmode(GPIO.BCM)

		ps2 = PS2(0, 0, 22)
		
		while True:
			ps2.GetKey()
			time.sleep(1)

	except Exception as e:
		raise e
	finally:
		ps2.CleanUp()
		GPIO.cleanup()

		
